// Example Django:
// {% block header %}
// <script type="text/javascript">
// 		$(document).ready(function() {
//			$("#id_country").Country('id_country', 'id_region', 'id_city', '{{ form.instance.region.pk }}');
//			$("#id_region").Region('id_region', 'id_city', '{{ form.instance.city.pk }}');
// 			$("#id_country").change();
//      });
// </script>
// {% endblock %}

site = '/worlddb'

function clean_select(id_select) {
	$("#" + id_select).empty();
	$("#" + id_select).addOption({'': '---------'}, true);
}

// Example of usage:
// update_regions('id_region', 'id_city', 5, 34);

function getValue(id) {
	value = $('#' + id).val()
	if(value.replace(/^\s*/, "").replace(/\s*$/, "") == '') {
		return '0';
	}
	return value;
}

function update_regions(id_component_countries, id_component_regions, id_component_cities, selected_region) {
	clean_select(id_component_regions);
	clean_select(id_component_cities);
	
	url = site + "/regions/" + getValue(id_component_countries)  + '/';
	$.getJSON(url, function(data, textStatus) {
			$.each(data, function(i, item) {
				value = item.pk;
				label = item.fields.name;
				$("#" + id_component_regions).addOption(value, label, false);
  			});
  			
  			$('#' + id_component_regions).val(selected_region);
			$("#" + id_component_regions).change();
    	}
    );
}

// Example of usage:
// update_cities('id_region', 'id_city', 27);

function update_cities(id_component_regions, id_component_cities, selected_city) {
	clean_select(id_component_cities);
	
	url = site + "/cities/" + getValue(id_component_regions) + '/';
	$.getJSON(url, function(data, textStatus) {
			$.each(data, function(i, item) {
				value = item.pk;
				label = item.fields.name;
				$("#" + id_component_cities).addOption(value, label, false);
  			});
  			
  			$('#' + id_component_cities).val(selected_city);
    	}
    );
}

jQuery.fn.Country = function(id_component_countries, id_component_regions, id_component_cities, selected_region) {
	this.change(function() { update_regions(id_component_countries, id_component_regions, id_component_cities, selected_region); });
}

jQuery.fn.Region = function(id_component_regions, id_component_cities, selected_city) {
	this.change(function() { update_cities(id_component_regions, id_component_cities, selected_city); });
}
